//
//  YSNewAddressCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/7/29.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSNewAddressCtrl.h"
#import "YSAddressDBModel.h"
#import "YSLocationDao.h"
#import "YSMineDataTool.h"


#define PROVINCE_COMPONENT  0
#define CITY_COMPONENT      1
#define AREA_COMPONENT  2

@interface YSNewAddressCtrl ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTF;
@property (weak, nonatomic) IBOutlet UILabel *pcaLabel;
@property (weak, nonatomic) IBOutlet UITextView *streetTV;
@property (weak, nonatomic) IBOutlet UITextField *postalLTF;

@property (strong, nonatomic) UIPickerView *pickerView;
@property (strong, nonatomic) NSArray *provincesArray;
@property (strong, nonatomic) NSMutableArray *cityArray;
@property (strong, nonatomic) NSMutableArray *areaArray;

@property (strong, nonatomic) YSLocationDao *locationDao;

@property (strong, nonatomic) YSAddress *address;

@property (strong, nonatomic) YSAddressDBModel *provBean;

@property (assign, nonatomic) NewAddressSourceType type;


@end

@implementation YSNewAddressCtrl

-(instancetype)initWithAddress:(YSAddress *)address{
    self = [super init];
    if(self){
        self.address = address;
    }
    return self;
}

-(instancetype)initWithType:(NewAddressSourceType)type{
    self = [super init];
    if(self){
        self.type = type;
    }
    return self;
}

- (IBAction)tapLocation:(id)sender {
    NSString *province =  [DefaultsHelper stringForKey:kLocationAddressProvince];
    NSString *city =  [DefaultsHelper stringForKey:kLocationAddressCity];
    NSString *area =  [DefaultsHelper stringForKey:kLocationAddressArea];
    NSString *street =  [DefaultsHelper stringForKey:kLocationAddressStreet];
    NSString *pca =  [NSString stringWithFormat:@"%@%@%@",province,city,area];
    if(ISBLANK(province)&&ISBLANK(city)&&ISBLANK(area)){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"定位失败" message:@"请在系统设置中开启定位服务\n或手动选择地址" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }else{
        [self.pcaLabel setText:pca];
    }
    [self.streetTV setText:street];
    
    //根据定位到的字符串去反查数据库得到区，县的id
    int provId = [_locationDao getProvinceId:province];
    int cityId = [_locationDao getCityId:provId cityName:city];
    NSString *areaId = [_locationDao getAreaId:cityId areaName:area];
    
    
    YSAddressDBModel *provBean = [[YSAddressDBModel alloc]init];
    provBean.provinceId = provId;
    provBean.provinceName = province;
    provBean.cityId = cityId;
    provBean.cityName = city;
    provBean.areaId = areaId;
    provBean.areaName = area;
    self.provBean = provBean;
    
    NSLog(@"\nprovince--:%@--city--:%@--area--:%@--street--:%@",province,city,area,street);
}

- (IBAction)tapAction:(id)sender {
    [self.view endEditing:YES];
    [self hidenPickerView:YES];
}

-(void)topSelectAddress:(UIGestureRecognizer *)sender{
    [self.view endEditing:YES];
    //弹出地址选择框
    [UIView animateWithDuration:0.4 animations:^{
        _pickerView.y = self.view.height-_pickerView.height;
    }];
}

-(void)saveAddress:(UIBarButtonItem *)item{
    
    //进行一系列的判空
    if(ISBLANK(_nameTF.text)|| ISBLANK(_phoneTF.text) || ISBLANK(_pcaLabel.text) ||  ISBLANK(_streetTV.text)){
        ShowTips(@"请把信息填写完整!");
        return;
    }
    
    if(!ISBLANK(_postalLTF.text)&& _postalLTF.text.length>6){
        ShowTips(@"邮编不合法");
        return;
    }
    
    if(![_phoneTF.text isValidatePhone]){
        ShowTips(@"手机号不合法");
        return;
    }
    
    [YSMineDataTool addAddressWithAddressee:_nameTF.text phoneCode:_phoneTF.text deliveryId:self.address==nil?self.provBean.areaId:self.address.deliveryId detailAdres:_streetTV.text postal:_postalLTF.text addressId:self.address==nil?0:self.address.addressId addressStr:_pcaLabel.text success:^(YSNewAddressRes *result) {
        if(result.isSucc){
            if(_type == NewAddressSourceAccountCenterType){
                YSAddress *address = [[YSAddress alloc]init];
                [address setAddressId:result.addressId];
                [address setAddressStr:_pcaLabel.text];
                [address setAddressee:_nameTF.text];
                [address setPhoneCode:_phoneTF.text];
                [address setDeliveryId:self.provBean.areaId];
                [address setDetailAdres:_streetTV.text];
                [address setPostal:_postalLTF.text];
                [[NSNotificationCenter defaultCenter]postNotificationName:kChooseAddressFinishNortif object:address];
            }else{
                 [[NSNotificationCenter defaultCenter]postNotificationName:kAddressItemChangeNortif object:nil];
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"新增地址"];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAddress:)];
    rightItem.tintColor = ThemeColor;
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UITapGestureRecognizer *tap =  [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(topSelectAddress:)];
    [self.pcaLabel addGestureRecognizer:tap];

    _locationDao = [[YSLocationDao alloc]init];
    _provincesArray = [NSArray arrayWithArray:[_locationDao getProvinces]];
    
    YSAddressDBModel *provbean = [_provincesArray firstObject];
    _cityArray = [NSMutableArray arrayWithArray:[_locationDao getCitys:provbean.provinceId]];
    
    YSAddressDBModel *citybean = [_cityArray firstObject];
    _areaArray = [NSMutableArray arrayWithArray:[_locationDao getAreas:citybean.cityId]];
    
    _pickerView = [[UIPickerView alloc]init];
    [_pickerView setBackgroundColor:[UIColor whiteColor]];
    CGFloat pickerH = 162;
    if(iPhone6){
        pickerH = 216;
    }else if(iPhone5s){
        pickerH = 180;
    }
    [_pickerView setFrame:CGRectMake(0, self.view.height, SCREENW, pickerH)];
    [_pickerView setDataSource:self];
    [_pickerView setDelegate:self];
    _pickerView.showsSelectionIndicator = YES;
    [_pickerView selectRow: 0 inComponent: 0 animated: YES];
    [self.view addSubview:_pickerView];
    
    if (self.address) {
        [self initData];
    }
}

-(void)initData{
    [_nameTF setText:self.address.addressee];
    [_phoneTF setText:self.address.phoneCode];
    NSString *areaId =  self.address.deliveryId;
    NSString *pcaName  = [_locationDao getDetaild:[areaId substringToIndex:6].intValue :[areaId substringToIndex:9].intValue :areaId];
    
    [_pcaLabel setText:pcaName];
    [_streetTV setText:self.address.detailAdres];
    [_postalLTF setText:self.address.postal];
}

-(void)hidenPickerView:(BOOL)hiden{
    if(hiden){
        if (_pickerView.y!= self.view.height) {
            [UIView animateWithDuration:0.4 animations:^{
                _pickerView.y = self.view.height;
            }];
        }
    }else{
        if (_pickerView.y!=self.view.height-_pickerView.height) {
            [UIView animateWithDuration:0.4 animations:^{
                _pickerView.y = self.view.height-_pickerView.height;
            }];
        }
    }
}


#pragma UIPICKERVIEW DATASOURCE & DELEGATE
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(component==0){
        return _provincesArray.count;
    }else if(component == 1){
        return _cityArray.count;
    }else{
        return _areaArray.count;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    BOOL isSelectProv = NO;
    switch (component) {
        case PROVINCE_COMPONENT:{
            //更新市array
            YSAddressDBModel *provbean = _provincesArray[row];
            _cityArray = [NSMutableArray arrayWithArray:[_locationDao getCitys:provbean.provinceId]];
            
            [pickerView reloadComponent:CITY_COMPONENT];
            [pickerView selectRow:0 inComponent:CITY_COMPONENT animated:NO];
            isSelectProv = YES;
        }
        case CITY_COMPONENT:{
            //更新县array
            YSAddressDBModel *citybean = _cityArray[isSelectProv?0:row];
            _areaArray = [NSMutableArray arrayWithArray:[_locationDao getAreas:citybean.cityId]];
            [pickerView reloadComponent:AREA_COMPONENT];
            [pickerView selectRow:0 inComponent:AREA_COMPONENT animated:NO];
            break;
        }
        case AREA_COMPONENT:{
            break;
        }
    }
    
    [self setProvCityAreaText];
}

/**
 *  这个名字取得有点不好不要介意
 *
 *  @return
 */
-(void)setProvCityAreaText{
    NSInteger provinceIndex = [_pickerView selectedRowInComponent: PROVINCE_COMPONENT];
    NSInteger cityIndex = [_pickerView selectedRowInComponent: CITY_COMPONENT];
    NSInteger areaIndex = [_pickerView selectedRowInComponent: AREA_COMPONENT];
    
    YSAddressDBModel *provBean = _provincesArray[provinceIndex];
    YSAddressDBModel *cityBean = _cityArray[cityIndex];
    YSAddressDBModel *areaBean = _areaArray[areaIndex];
    
    [_pcaLabel setText:[NSString stringWithFormat:@"%@%@%@",provBean.provinceName,cityBean.cityName,areaBean.areaName]];
    
    provBean.cityId = cityBean.cityId;
    provBean.cityName = cityBean.cityName;
    provBean.areaId = areaBean.areaId;
    provBean.areaName = areaBean.areaName;
    
    self.provBean = provBean;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    switch (component) {
        case PROVINCE_COMPONENT:{
            YSAddressDBModel *temp =  _provincesArray[row];
            return temp.provinceName;
            break;
        }
        case CITY_COMPONENT:{
            YSAddressDBModel *temp =  _cityArray[row];
            return temp.cityName;
            break;
        }
        case AREA_COMPONENT:{
            YSAddressDBModel *temp =  _areaArray[row];
            return temp.areaName;
            break;
        }
    }
    return @"";
}


-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setBackgroundColor:[UIColor clearColor]];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    pickerLabel.text=[self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

@end
